package com.katze.boot.applet.asn1.anlysis;

import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.stream.Stream;

public abstract class AnalysisWriter implements AutoCloseable{
    private Path info;
    private BufferedWriter writer = null;
    private int count = 0;
    private String status = "ready";

    protected void initDir(Path storageDir){
        try {
            if (Files.notExists(storageDir)) Files.createDirectories(storageDir);
            Path storage = storageDir.resolve("data.txt");
            try (Stream<Path> stream = Files.find(storageDir, 1,  (p, a) -> p.getFileName().toString().startsWith("info_"))){
                this.info = stream.findFirst().orElseGet(() -> storageDir.resolve(String.format("info_%d_%s", count, status)));
            }
            if (Files.exists(storage)) Files.delete(storage);
            this.writer = Files.newBufferedWriter(storage, StandardOpenOption.CREATE, StandardOpenOption.APPEND);
            Files.write(this.info, "".getBytes(),  StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void append(String data) throws IOException {
        if (!"decode".equals(this.status)){
            this.status = "decode";
            this.info = Files.move(this.info, this.info.resolveSibling(String.format("info_%d_%s", count, status)));
        }
        this.count ++;
        this.writer.write(data);
    }

    @Override
    public void close() throws IOException {
        if (writer != null) {
            if ("ready".equals(this.status) && this.count == 0) {
                // 此场景为异常情况下出现
                this.status =  "error";
            } else {
                // 此场景为常规解析失败
                this.status = this.count > 0? "success":"error";
            }
            this.info = Files.move(this.info, this.info.resolveSibling(String.format("info_%d_%s", count, status)));
            writer.close();
        }
    }
}
